function result=TSVM(x,y,l_ind)
%FUNCTION `TSVM` @return {kfcv, model, acc}
%   @x      features
%   @y      labels
%   @l_ind  label indexs
    %tic;
    set(0,'RecursionLimit',2000);
    addpath('tsvm/bin','tsvm/matlab');

    gamma = compute(x); 
    pama = ['-t 2 -g ' num2str(gamma) ' -c 1'];
    tic;
    %%l_ind
    result.kfcv = KFCVTSVM(x,y,l_ind,5,pama); %kfcv result
    ty = zeros(size(y));
    ty(l_ind) = y(l_ind);
    result.model = svmlearn(x, ty, pama);
    
    u_ind = 1:length(y);
    u_ind(l_ind) = [];
    [~,pred] = svmclassify(x,y,result.model);
    result.acc = sum(sign(pred(u_ind))==y(u_ind))/length(u_ind); %testing acc
    %fprintf('tsvm! passed time: %g seconds\n',toc);

end

function kfcv = KFCVTSVM(x,y,l_ind,K,param)
%FUNCTION kfcv do K times K-fold CV and @return kfcv{acc,auc}
%   @x      feature
%   @y      labels, 0 means missing
%   @l_ind  labels' index
%   @K      
%   @param  parameters for model

    %%unlabled = 1:length(y);
    %%unlabled(l_ind) = [];
    %%drop labeled index from unlabeled
    %%testdata = [];
    acc = zeros(K, K);
    auc = zeros(K, K);
    for j=1:K
        [train_ind,test_ind] = KFoldSplit(y,l_ind,K);
        for k = 1:K
            ty = zeros(size(y));
            ty(train_ind{k}) = y(train_ind{k});
            [~,pred] = svmclassify(x,y,svmlearn(x,ty,param));
            acc(j,k) = sum(sign(pred(test_ind{k}))==y(test_ind{k}))/length(test_ind{k});
            auc(j,k) = AUC(y(test_ind{k}),pred(test_ind{k}));
            %%testdata = [testdata sign(pred(unlabled))];
        end
    end
    kfcv.acc = sum(sum(acc))/(K*K);
    kfcv.auc = sum(sum(auc))/(K*K);
    fprintf('TSVM    kfcv.acc:%f, kfcv.auc:%f\n',kfcv.acc, kfcv.auc);
    %%kfcv.testdata = testdata;
end


function gamma = compute(X)
    dis = compute_dis(X);
    [~,n]=size(dis);
    all_s = sum((sum(dis))')/2;
    numb = (n*(n-1))/2;
    gamma = 1/(all_s/numb);
end

function dis = compute_dis(X)
    % X: input data, n*d
    % dis: distance matrix, n*n
    v = dot(X,X,2);
    dis = bsxfun(@plus,v,v') - 2*(X*X');
end
